package sync;

public class unsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100,"存款");
        User user = new User(account, 50, "你");
        User girlfriend = new User(account, 80, "girlfriend");
        user.start();
        girlfriend.start();
    }
}

class Account {
     int money;//余额
     String name;//卡名

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }

}

class User extends Thread {
     Account account;
     int getMoney;
     int nowMoney;

    public User(Account account, int getMoney, String name) {
        super(name);
        this.account = account;
        this.getMoney = getMoney;
    }

    @Override
    public void run() {
        //synchronized代码块默认锁this，需要锁变化的量才安全
        synchronized (account){
            //取款
            if (account.money-getMoney<0) {//判断
                System.out.println(Thread.currentThread().getName()+"钱不够");
                return;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money -= getMoney;
            System.out.println(account.name+"余额："+account.money);
            nowMoney += getMoney;
            System.out.println(Thread.currentThread().getName()+"手里的钱"+nowMoney);
        }

    }
}